// pages/public_customer/public_customer.js
let listBehavior = require('../../behavior/list')
Page({

  behaviors: [ listBehavior, ],
  /**
   * 页面的初始数据
   */
  data: {
    tableid: '', //模块id
    tableName: '',  //模块名
    searchPlc: '搜索',  //搜索占位文字
    list:[],  //显示数据

    fieldList: [], //所有字段列表

    displayField: [],  //显示字段列表

    keyList: [],  //搜索关键字
    searchList: [], //快速查询字段列表
    advList: [],  //高级查询列表

    sumList: [], //底部统计字段集合
    cashierBtn: false,

    where: [],


    query: { //公海筛选条件
      CompareWith: 'customer.high_seas_row_id',
      Operator: 'is not null',
      CompareValue: '',
      or: 0
    },
    //公海选择
    highSeaList: [],
    showFlag: false,
    row_id: 0 //转移客户行id

  },

  //获取数据
  getDataList(){
    let url = 'DynamicQuery/query_dynamic_v3',
      {tableid, where,page,limit,query} = this.data,
      post = {"table_id": tableid,"oby": tableid + ".row_id desc",page,limit};
    if (!where || !where[0]){
      where = [query]
    }
    post.SearchWhere = {filters: where ,type: 'and'};
    wx.$post(3,url,post).then(res => {
      let total = 0,
        {list} = this.data,
        sumArr = [],
        obj = {};
      if (res.data.row){
        total = res.data.total;
        let rows = res.data.row;
        if(page !== 1) rows = [ ...list,...rows, ]
        obj = {total,list: rows,page};
      }
      sumArr.push({name: '记录数',num: total});
      if (res.data.sum && res.data.sum[0]) {
        wx.$each(res.data.sum[0],(key,val)=>{
          sumArr.push({name: key,num: wx.$util.formatNum(val)});
        })
      }
      obj.sumList = sumArr;
      this.setData(obj);

    });
  },

  //搜索
  searchData({detail}){
    let where = [];

    if (!detail.adv){
      this.data.query = { //默认筛选条件
        CompareWith: 'customer.high_seas_row_id',
        Operator: 'is not null',
        CompareValue: '',
        or: 0
      };
      where = [this.data.query];
    }else {
      this.data.query = JSON.parse(detail.adv).filters[0]
    }
    where = where.concat(detail.comb)
    this.data.where = where;
    this.getFirstPage();
  },
  //刷新列表
  refreshData(){
    this.getFirstPage();
  },

  //获取表信息
  getEntityParam(){
    let post = {}
    wx.$post(3,'Entity_param/query_entity_param',{table_id: this.data.tableid}).then(res=>{
      if (res.errcode != 0)return;
      this.setData({
        entityParam: res.data.row[0],
        tableName: res.data.row[0].table_name
      })
    })
  },
  //获取列显示--221109 yan 取消显示列显示
  getFieldDisplay(){
    let url = 'Entity_field_display/query_entity_field_display',
      entity = this.data.tableid,
      post = {
        "table_id": entity,
        "display_id": ''
      };
    wx.$post(3,url,post,false,true).then(res => {
      this.setData({
        displayField: res.showFields
      });

      this.getDataList();
    })
  },
  //获取列表页布局--221109 yan 获取列表页布局
  getListLayout(tableid){
    let url = 'Custom/get_html_WXMiniProgram',
      post = {'table_id': tableid};
    return new Promise(resolve => {
      wx.$post(1,url,post).then((res)=>{
        if (res.errcode != 0)return;
        let data = res.data.row && res.data.row[0],
          layout = data && data.html_js_query  || '';
        try {
          layout = JSON.parse(layout);
        }catch (e) {}

        resolve(layout);
      })

    })
  },


  // 接口
  ready() {
    let { tableid, } = this.data,
      p0 = this.getListLayout(tableid),
      p1 = this.getAllEntityFields(tableid),
      p2 = this.getQuickFilter(tableid)
    // 1.获取列表布局，2.获取所有字段 3.获取快速查询条件，3.1获取引用筛选的主显示字段，3.2获取引用筛选的选项，4.获取所有字段得到单选多选的选项，3.获取高级查询tab
    Promise.all([p0, p1, ]).then(res => {
      let layout = res[0],
        fieldList = res[1],
        displayField = [];

      wx.$each(layout,(i,item)=>{
        let field = fieldList.find(ite=>{
          return ite.field_id === item || ite.fieldName === item
        });
        field && displayField.push(field);
      });

      this.setData({
        displayField: displayField
      });
      this.getDataList();


      p2.then(res=>{
        let searchList = res,
          radioCheckList = {}
        fieldList.forEach(row => {
          let { type, field_id, } = row
          if(['picklist', 'multiple'].includes(type)) radioCheckList[field_id] = JSON.parse(row.option)
        })

        searchList && searchList.forEach(item => {
          let { type, field_id, } = item;
          if(['picklist', 'multiple', ].includes(type)) item.optionList = radioCheckList[field_id]
        })

        this.setData({
          searchList,
        })
      })
    })

    this.getAdvTab(tableid);
    // this.getCashierEntity();

  },
  // 2.获取模块所有字段
  getAllEntityFields(tableid) {
    return new Promise((resolve, reject) => {
      wx.$post(4, 'QX/PRO_select_field', { table: tableid, fieldname: '', }).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row;
        resolve(rows);
      })
    })
  },
  // 3.获取筛选条件项目
  getQuickFilter(tableid) {
    return new Promise((resolve, reject) => {
      wx.$post(3, 'Entity_query_model/query_entity_query_model', { table_id: tableid, }, '', true).then(res => {
        let { showFields, query_field, } = res,
          obj = {}

        this.setData({
          keyList: query_field,
        })

        showFields && showFields.forEach(item => {
          let { type, mainEntity, } = item
          if(['reference1', 'reference', ].includes(type)) {
            if(!obj[mainEntity]) obj[mainEntity] = []
            obj[mainEntity].push(item)
          }
        })
        let proArr = []
        Object.keys(obj).forEach(entity => {
          proArr.push(this.getRefOptionList(entity, obj[entity]))
        })

        Promise.all(proArr).then(res => {
          resolve(showFields)
        })
      })
    })
  },
  // 获取引用字段的选项
  getRefOptionList(tableid, arr) {
    return new Promise((resolve, reject) => {
      // 1.1获取模块的主显示字段
      let p0 = new Promise((resolve, reject) => {
        wx.$post(3, 'Entity_param/query_entity_param', { table_id: tableid, }).then(res => {
          if(res.errcode !== 0) return
          resolve(res.data.row[0].entity_key)
        })
      })
      // 1.2获取引用字段的选项
      let p1 = new Promise((resolve, reject) => {
        wx.$post(3, 'DynamicQuery/query_dynamic', { oby: `${tableid}.row_id desc`, table_id: tableid, }).then(res => {
          if(res.errcode !== 0) return
          resolve(res.data.row[0])
        })
      })

      Promise.all([p0, p1, ]).then(res => {
        let optionName = res[0],
          optionList = res[1]
        arr.forEach(item => {
          item.optionName = optionName
          item.optionList = optionList
        })
        resolve()
      })
    })
  },
  // 3.获取高级查询tab--公海列表
  getAdvTab(tableid) {
    let post = {
      row_id: 0,
      high_seas_name: ''
    }
    wx.$post(1, 'AllHighSeas/query_all_high_seas_set', post).then(res => {
      if(res.errcode !== 0) return;
      let data = res.data.row || [],
        highSeaList = [],
        employee_row_id = wx.getStorageSync('employee_row_id'),
        advList = [];
      data.forEach(item=>{
        if (employee_row_id == item.high_seas_admin_row_id) {
          highSeaList.push(item);
        }
        if (item.is_used){
          let query = {
            type: 'and',
            filters:  [
              {
                CompareWith: 'customer.high_seas_row_id',
                Operator: '=',
                CompareValue: item.row_id,
                or: 0
              }
            ]
          };
          query = JSON.stringify(query);
          advList.push({
            combination_query_json: query,
            combination_name: item.high_seas_name
          })
        }
      });
      this.setData({
        advList,highSeaList
      });
    })
  },

  //获取出纳模块
  getCashierEntity () {
    let { tableid, } = this.data;
    wx.$post(1,'AllCashierEntity/select_all_cashier_entity',{table_id: tableid}).then(res=>{
      if (res.errcode != 0){return}
      let data = res.data.row || [];
      if (data && data.length > 0){
        this.setData({
          cashierEntity: data[0],
          cashierBtn: true})
      }
    })
  },

  //删除
  bindDelete(e){
    let data = e.currentTarget.dataset,
      rid = data.rid,
      index = data.index;
    if (!this.data.auth.tableDelete) {
      wx.$toast('抱歉，您没有权限删除该模块数据！');
      return
    }
    wx.showModal({
      title: '提示',
      content: '确认删除该记录？',
      success: (res) => {
        if(res.confirm) {
          wx.showLoading();
          this.deleteData(rid).then(()=>{
            let list = this.data.list;
            list.splice(index, 1);
            wx.$toast('删除成功！');
            this.setData({
              list
            });
          });
        }
      },
    })
  },
  //删除记录
  deleteData(rid){
    return new Promise(resolve => {
      wx.$post(3,'DynamicUpdate/dynamic_delete',{row_ids: rid.toString(),table_id: this.data.tableid}).then(res=>{
        if (res.errcode != 0)return;
        resolve();
      })
    })
  },
  //删除客户--客户表删除需要进行数据验证接口404
  deleteCustomer(rid){
    let url =  'DynamicUpdate/CheckCustomerBusiness?Id=' + rid.toString();
    wx.$post(3,url,null,true,true).then(async res=>{
      console.log(res);
      if (res.Code == 0){
        //删除操作

      } else {
        var msg = '';
        var code = parseInt(res.Code);
        while (code == -2) {
          sleep(500);
          url = 'DynamicUpdate/CheckCustomerBusiness?guid=' + res.GUID;
          await wx.$post(3,url,null,true,true).then(dt=>{

            code = parseInt(dt.Code);
            msg = dt.Msg;
            if (code == -2) {
              wx.$toast(dt.Speed);
            }
          });

        }
        if (code == 0){
          //删除操作

        } else {
          wx.$toast(msg);
        }
      }
    })
  },
  //跳转页面
  navTo(e){
    let {url,type} = e.currentTarget.dataset;
    if (type === 'add' && !this.data.auth.tableAppend) {
      wx.$toast('抱歉，您没有权限新增该模块数据！');
      return
    }
    wx.navigateTo({
      url: url
    })
  },

  bindHighSea(e){
    let {rid} = e.currentTarget.dataset;

    this.setData({
      showFlag: !this.data.showFlag,
      row_id: rid
    })
  },

  //领取公海
  receiveCustomer(e){
    let url = 'AllHighSeas/update_high_seas_out',
      post = {row_id: e.currentTarget.dataset.rid};
    wx.showModal({
      title: '提示',
      content: '确认领取该客户？',
      success: (res) => {
        if(res.confirm) {
          wx.showLoading();
          wx.$post(1,url,post).then(res=>{
            if (res.errcode != 0)return;
            wx.$toast('领取成功！');
            this.getFirstPage();
          })
        }
      },
    })
  },
  //转移公海
  changeHighSeas({detail}){
    let seasId = detail.row_id,
      {row_id,query} = this.data,
      url = 'AllHighSeas/update_high_seas_change',
      post = {
      high_seas_row_id: seasId,
      query: {
        table_id: 'customer',
        repeat_row_id_list: row_id,
        SearchWhere: [query]
      }
    };
    wx.$post(1,url,post).then(res=>{
      if (res.errcode != 0)return;
      wx.$toast('转移成功！');
      this.getFirstPage();
    })

  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    let entity = options.entity;

    let where = wx.getStorageSync('echarts');
    if (where){
      wx.removeStorageSync('echarts');
      this.setData({where});
    }

    wx.$getAuth(entity).then(res=>{
      if (!res.tableSee) {
        wx.$toast('抱歉，您没有权限查看该模块数据！',1000).then(()=>{
          wx.navigateBack({ delta:1 });
        });
        return
      }
      this.setData({
        auth: res,
        tableid: entity
      });
      this.getEntityParam();
      this.ready();
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
});
